<template>
<view>
<!-- pages/search/search.wxml -->
<view class="search_row">
    <input :value="inpValue" class="search_inp" placeholder="请输入您要搜索的商品" @input="handleInput">
    <button @tap="handleCancel" class="search_but" :hidden="!isFocus">取消</button>
</view>
<view class="search_content">
    <navigator v-for="(item, index) in goods" :key="index" :url="'/pages/goods_detail/goods_detail?goods_id=' + item.goods_id" class="search_item">
        {{item.goods_name}}
    </navigator>
</view>
</view>
</template>

<script>
// pages/search/search.js
import { request } from "../../request/index.js";
import regeneratorRuntime from "../../lib/runtime/runtime";

export default {
  data() {
    return {
      goods: [],
      // 取消 按钮 是否显示
      isFocus: false,
      // 输入框的值
      inpValue: "",
      TimeId: -1
    };
  },

  components: {},
  props: {},
  methods: {
    // 输入框的值改变 就会触发事件
    handleInput(e) {
      // console.log(e);
      // 1. 获取输入框的值
      const {
        value
      } = e.detail; // 2. 检测合法性

      if (!value.trim()) {
        this.setData({
          goods: [],
          isFocus: false
        }); // 值不合法

        return;
      } // 3. 备发送请求获取数据


      this.setData({
        isFocus: true
      });
      clearTimeout(this.TimeId);
      this.TimeId = setTimeout(() => {
        this.qsearch(value);
      }, 1000);
    },

    // 发送请求获取搜索建议 数据
    async qsearch(query) {
      const res = await request({
        url: "/goods/qsearch",
        data: {
          query
        }
      }); // console.log(res);

      this.setData({
        goods: res
      });
    },

    // 点击 取消按钮
    handleCancel() {
      this.setData({
        inpValue: "",
        isFocus: false,
        goods: []
      });
    }

  }
};
</script>
<style>
@import "./search.css";
</style>